package com.bjbn.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.UUID;

import com.bjbn.config.RocketMQConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/sync")
public class FimsSyncController {

    @Autowired
    private RocketMQConfig rocketMQConfig;

    /**
     * 4.1.2.7.4机场基础请求消息（RQAP）
     *
     * @return
     */
    @GetMapping("/rqap")
    public String syncRQAP() {
        // 添加ACL权限认证
        RPCHook rpcHook = new AclClientRPCHook(new SessionCredentials(rocketMQConfig.getTaom().getConsumer().getKey(),
                rocketMQConfig.getTaom().getConsumer().getSecret()));
        // 添加ACL权限认证，并开启消息轨迹（ProducerGroupName-生产者组，rpcHook-ACL认证，true-消息轨迹开启）
        DefaultMQProducer producer = new DefaultMQProducer("MQGROUP-DTS", rpcHook, true, null);
        // 填入元数据连接地址
        producer.setNamesrvAddr(rocketMQConfig.getTaom().getNameServer());
        // 创建实例时，如果开启了SSL，请添加此行代码。
        producer.setUseTLS(true);
        try {
            producer.start();
            String topic = "T-CAN-AOIP-INTEGRATION_REQUEST_EVENT";
            // keys 由字母、中划线及数字组成，区分大小写。
            // 命名规则：{Topic名称}-{时间字符串}-{UUID}
            // Topic名称：消息发布的TOPIC名称。
            // 时间字符串：消息生成时间，格式为：yyyymmddhhmmss。
            // UUID：取随机生成的UUID的前8位。
            // keys示例 CAN-IASP-PUBLIC-20230616150105-3c45e6ab
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String timeStr = LocalDateTime.now().format(formatter);
            String keys = topic + "-" + timeStr + "-" + UUID.randomUUID().toString().substring(0, 8);

            String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MSG><META><SNDR>DTS</SNDR><RCVR>FIMS</RCVR><SEQN>1</SEQN><DDTM>"
                    + timeStr
                    + "</DDTM><TYPE>REQE</TYPE><STYP>RQAP</STYP></META><RQST></RQST></MSG>";

            Message msg = new Message("T-CAN-AOIP-INTEGRATION_REQUEST_EVENT",
                    "RQAP",
                    keys,
                    body.getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.send(msg);

            System.out.println(keys);
            System.out.println(body);
            System.out.println(Arrays.toString(body.getBytes(RemotingHelper.DEFAULT_CHARSET)));

            System.out.printf("%s%n", sendResult);

            return sendResult.toString();

        } catch (Exception e) {
            e.printStackTrace();

        }
        producer.shutdown();

        return "未知错误";
    }

    // 4.1.2.15.4航班保障节点基础信息请求消息（RQBD）
    @GetMapping("/rqbd")
    public String syncRQBD() {
        // 添加ACL权限认证
        RPCHook rpcHook = new AclClientRPCHook(new SessionCredentials(rocketMQConfig.getTaom().getConsumer().getKey(),
                rocketMQConfig.getTaom().getConsumer().getSecret()));
        // 添加ACL权限认证，并开启消息轨迹（ProducerGroupName-生产者组，rpcHook-ACL认证，true-消息轨迹开启）
        DefaultMQProducer producer = new DefaultMQProducer("MQGROUP-DTS", rpcHook, true, null);
        // 填入元数据连接地址
        producer.setNamesrvAddr(rocketMQConfig.getTaom().getNameServer());
        // 创建实例时，如果开启了SSL，请添加此行代码。
        producer.setUseTLS(true);
        try {
            producer.start();
            String topic = "T-CAN-AOIP-INTEGRATION_REQUEST_EVENT";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String timeStr = LocalDateTime.now().format(formatter);
            String keys = topic + "-" + timeStr + "-" + UUID.randomUUID().toString().substring(0, 8);

            String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MSG><META><SNDR>DTS</SNDR><RCVR>FIMS</RCVR><SEQN>1</SEQN><DDTM>"
                    + timeStr
                    + "</DDTM><TYPE>REQE</TYPE><STYP>RQBD</STYP></META><RQST></RQST></MSG>";

            Message msg = new Message("T-CAN-AOIP-INTEGRATION_REQUEST_EVENT",
                    "RQBD",
                    keys,
                    body.getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.send(msg);
            return sendResult.toString();

        } catch (Exception e) {
            e.printStackTrace();

        }
        producer.shutdown();

        return "未知错误";
    }

    // 4.1.2.11.4机位信息请求消息（RQST）
    @GetMapping("/rqst")
    public String syncRQST() {
        // 添加ACL权限认证
        RPCHook rpcHook = new AclClientRPCHook(new SessionCredentials(rocketMQConfig.getTaom().getConsumer().getKey(),
                rocketMQConfig.getTaom().getConsumer().getSecret()));
        // 添加ACL权限认证，并开启消息轨迹（ProducerGroupName-生产者组，rpcHook-ACL认证，true-消息轨迹开启）
        DefaultMQProducer producer = new DefaultMQProducer("MQGROUP-DTS", rpcHook, true, null);
        // 填入元数据连接地址
        producer.setNamesrvAddr(rocketMQConfig.getTaom().getNameServer());
        // 创建实例时，如果开启了SSL，请添加此行代码。
        producer.setUseTLS(true);
        try {
            producer.start();
            String topic = "T-CAN-AOIP-INTEGRATION_REQUEST_EVENT";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String timeStr = LocalDateTime.now().format(formatter);
            String keys = topic + "-" + timeStr + "-" + UUID.randomUUID().toString().substring(0, 8);

            String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MSG><META><SNDR>DTS</SNDR><RCVR>FIMS</RCVR><SEQN>1</SEQN><DDTM>"
                    + timeStr
                    + "</DDTM><TYPE>REQE</TYPE><STYP>RQST</STYP></META><RQST></RQST></MSG>";

            Message msg = new Message("T-CAN-AOIP-INTEGRATION_REQUEST_EVENT",
                    "RQST",
                    keys,
                    body.getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.send(msg);
            return sendResult.toString();

        } catch (Exception e) {
            e.printStackTrace();

        }
        producer.shutdown();

        return "未知错误";
    }
}
